package tw.com.softleader.steven;

import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;

import com.google.common.collect.Lists;

public class InfiniteExecute implements Command {
	
	public InfiniteExecute() {
		super();
		System.out.println("嘗試取得貼圖次數為無限次。");
	}

	@Override
	public String execute(String authKey, String accessToken, String picNo) {
		StringBuffer message = new StringBuffer();
		HttpClient client = new DefaultHttpClient();
		System.out.println("開始抓編號[" + picNo + "]圖");
		HttpPost request = new HttpPost(GET_LINE_PIC);
		List<NameValuePair> nameValuePairs = Lists.newArrayList();
		nameValuePairs.add(new BasicNameValuePair("StickerId", picNo.trim()));
		nameValuePairs.add(new BasicNameValuePair("Authkey", authKey));
		nameValuePairs.add(new BasicNameValuePair("AccessToken", accessToken));
		nameValuePairs.add(new BasicNameValuePair("PHost", ""));
		nameValuePairs.add(new BasicNameValuePair("PPort", ""));
		while (true) {
			String responseContent = "";
			try {
				request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = client.execute(request);
				responseContent = Jsoup.parse(EntityUtils.toString(response.getEntity())).select("p").get(1).text();
			} catch (Exception e) {
			}
			System.out.println(responseContent);
			if (responseContent.contains("貼圖成功下載到貼圖小舖") || responseContent.contains("您已有本貼圖")) {
				message.append("編號: [" + picNo.trim() + "]" + responseContent + "。\n");
				break;
			}
		}
		return message.toString();
	}

}
